/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.z100h.supplychain.supplier.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.z100h.supplychain.supplier.entity.Contract;
import com.z100h.supplychain.supplier.entity.Supplier;
import com.z100h.supplychain.supplier.service.ContractService;
import com.z100h.supplychain.supplier.service.SupplierService;

/**
 * 供应商合同Controller
 * @author madara
 * @version 2018-09-20
 */
@Controller
@RequestMapping(value = "${adminPath}/supplier/contract")
public class ContractController extends BaseController {

	@Autowired
	private ContractService contractService;

	@Autowired
	private SupplierService supplierService;

	@ModelAttribute
	public Contract get(@RequestParam(required = false) String id) {
		Contract entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = contractService.get(id);
		}
		if (entity == null) {
			entity = new Contract();
		}
		return entity;
	}

	/**
	 * 供应商合同列表页面
	 */
	@RequiresPermissions("supplier:contract:list")
	@RequestMapping(value = { "list", "" })
	public String list() {
		return "supplychain/supplier/contractList";
	}

	/**
	* 供应商合同列表数据
	*/
	@ResponseBody
	@RequiresPermissions("supplier:contract:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Contract contract, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<Contract> page = contractService.findPage(new Page<Contract>(request, response), contract);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑供应商合同表单页面
	 */
	@RequiresPermissions(value = { "supplier:contract:view", "supplier:contract:add",
			"supplier:contract:edit" }, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(HttpServletRequest request, Contract contract, Model model) {
		model.addAttribute("contract", contract);
		if (StringUtils.isBlank(contract.getId())) {// 如果ID是空为添加
			model.addAttribute("isAdd", true);
		}

		/**
		 * 供应商列表
		 */
		Supplier supplier = new Supplier();
		User logUser = UserUtils.getUser();
		supplier.setCompanyId(logUser.getCompany().getId());// 根据公司查询
		/*
		 * supplier.setDepartmentId(logUser.getOffice().getId()); supplier.setStationId(logUser.getStation().getId());
		 */
		List<Supplier> supplierList = supplierService.findList(supplier);
		request.setAttribute("supplierList", supplierList);

		return "supplychain/supplier/contractForm";
	}

	/**
	 * 保存供应商合同
	 */
	@RequiresPermissions(value = { "supplier:contract:add", "supplier:contract:edit" }, logical = Logical.OR)
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, Contract contract, Model model,
			RedirectAttributes redirectAttributes) throws Exception {
		if (!beanValidator(model, contract)) {
			return form(request, contract, model);
		}
		// 新增或编辑表单保存
		// TODO

		contractService.save(contract);// 保存
		addMessage(redirectAttributes, "保存供应商合同成功");

		return "redirect:" + Global.getAdminPath() + "/supplier/contract/?repage";
	}

	/**
	 * 删除供应商合同
	 */
	@ResponseBody
	@RequiresPermissions("supplier:contract:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Contract contract, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		contractService.delete(contract);
		j.setMsg("删除供应商合同成功");
		return j;
	}

	/**
	 * 批量删除供应商合同
	 */
	@ResponseBody
	@RequiresPermissions("supplier:contract:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			contractService.delete(contractService.get(id));
		}
		j.setMsg("删除供应商合同成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("supplier:contract:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(Contract contract, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "供应商合同" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<Contract> page = contractService.findPage(new Page<Contract>(request, response, -1), contract);
			new ExportExcel("供应商合同", Contract.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出供应商合同记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	/**
	 * 导入Excel数据
	
	 */
	@RequiresPermissions("supplier:contract:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Contract> list = ei.getDataList(Contract.class);
			for (Contract contract : list) {
				try {
					contractService.save(contract);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条供应商合同记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条供应商合同记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入供应商合同失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/supplier/contract/?repage";
	}

	/**
	 * 下载导入供应商合同数据模板
	 */
	@RequiresPermissions("supplier:contract:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "供应商合同数据导入模板.xlsx";
			List<Contract> list = Lists.newArrayList();
			new ExportExcel("供应商合同数据", Contract.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/supplier/contract/?repage";
	}

}